<?php
/**
 * FastApp.
 * 3/17/25
 * @Author deepsea
 * @Contact (telegram:deepsea159)
 */

namespace App\Hoenix\Job;

use App\Fastapp\Model\FastappRobotGroup;
use App\Hoenix\Model\HoenixIndex;
use Hyperf\AsyncQueue\Job;
use Telegram\Bot\Api;

class TgChatInfoJob extends Job
{

    public function __construct(public int $bot_id, public string $chat_username)
    {
    }

    public function handle(): void
    {
        try {
            if (!str_starts_with($this->chat_username, '@')) $this->chat_username = '@' . $this->chat_username;
            $config = redis()->hGetAll('bot:' . $this->bot_id);
            $bot = new Api($config['token']);
            $res = $bot->getChat(['chat_id' => $this->chat_username]);
            if ($res->type == 'channel') $type = 2;
            elseif ($res->type == 'private') $type = 0;
            else $type = 1;

            if (!HoenixIndex::query()->where(['chat_id' => $res->id, 'type' => $type])->exists()) {
                $map['c_at'] = date('Y-m-d H:i:s');
                $map['title'] = $res->title;
                $map['url'] = 'https://t.me/' . $this->chat_username;
                $map['username'] = $this->chat_username;
                $map['desc'] = $res->description;
                HoenixIndex::query()->create($map);
            }
            $md = FastappRobotGroup::query()->where(['source' => 1, 'group_id' => $res->id])->first();
            if (!$md) $md = new FastappRobotGroup();
            $in = [
                'source' => 1,
                'type' => $type,
                'shop_id' => $config['shop_id'] ?? 0,
                'group_id' => $res->id,
                'name' => $res->title,
                'desc' => $res->description,
                'username' => substr($this->chat_username, 1)
            ];
            $md->fill($in)->save();
            $num = $bot->getChatMemberCount(['chat_id' => $this->chat_username]);
            if ($num) $md->fill(['num' => $num])->save();
        } catch (\Throwable $throwable) {
            sys_notify($throwable->getMessage() . $throwable->getTraceAsString());
        }
    }
}